<!DOCTYPE html>
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
<title>化妆镜设置</title>
<link href="//www.foodsai.com/weather/ionic.css" rel="stylesheet"> 
<style>
#debug {
    margin-top:400px;
    background-color: white;
    height: 200px;
    overflow: scroll;
    color: black;
    font-size: 12px;
}
#debug p {
    padding: 3px 5px;
    word-wrap: break-word;
}
.gray {
    background-color: #ddd;
}
#debug span {
    display: block;
    word-wrap: break-word;
    margin-bottom: 2px;
}
</style>
</head>
<body style="background:#eee;">
<div class="scroll-content" ng-controller="MyCtrl">
        <div class="list">
            <label class="item item-input item-select">
                <div class="input-label icon-left ion-location">&nbsp位置</div>
                <select ng-model="data_GPS" ng-options="v.id as v.name for v in a_data" ng-change="reloadPage()" ng-init="InitPage()">
                    <option value ="101010100">----</option>
                </select>
            </label>
            <div class="item item-body" style="background:#eee;color: #777;font-size: 14px;">
    选择化妆镜所在地理位置
  </div>
          <label class="item item-input">  
         <div class="input-label icon-left ion-email">&nbsp镜面留言</div> 
         </label>
           <div class="item item-body" style="background:#eee;color: #777;font-size: 14px;">
    可以发送不超过36个字在化妆镜面显示。
  </div>
    <label class="item item-input">  
    <textarea placeholder="请输入您的留言…" rows="3" id="message" style="font-size: 20px;line-height:30px;"></textarea>
  </label>
 <button class="button button-full button-clear button-positive icon ion-ios-paperplane-outline" style="background:#4acfbc; color:white" ng-model="Send_word"  ng-click="tapSend()">发送</button>
</div>
</div>
<div id="debug"></div>
<div class="bar-footer" style="bottom:0;position:absolute;width:100%">
</div>

<script src="http://api.easylink.io/assets/js/mqttws31.js"></script>
<script src="http://api.easylink.io/bower_components/ionic/js/ionic.bundle.min.js"></script>
<script>
    // 从url中获取某个参数的值
function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
    // 得到设备ID
var device_id = getParameterByName('device_id');
if ( device_id !== null ){
    ez_connect(device_id);
}
    // 如果设备ID不为空，则执行连接MQTT的操作
function dump_obj(myObject) {
    var s = '';
    for (var property in myObject) {
        s += '<span>' + property +": " + myObject[property] + '</span>';
    }
    return s;
}
var i = 0;
console.log = (function(old_funct, div_log) {
    return function(text) {
        old_funct(text);
        var p = '';
        if (i%2 == 0)
            p = '<p>';
        else
            p = '<p class=\'gray\'>';
        if (typeof text === "object")
            div_log.innerHTML += p + JSON.stringify(text) + '</p>';
        else
            div_log.innerHTML += p + text + '</p>';
        div_log.scrollTop = div_log.scrollHeight;
        i += 1;
    };
} (console.log.bind(console), document.getElementById("debug")));
console.error = console.debug = console.info =  console.log
function ez_connect(device_id) {
    var access_token = getParameterByName('access_token');
    //document.getElementById('device_id').innerHTML = device_id;
    var wsbroker = "api.easylink.io";  //mqtt websocket enabled broker
    var wsport = 1983 // port for above
    var client = new Paho.MQTT.Client(wsbroker, wsport, "v1-web-" + parseInt(Math.random() * 1000000, 10));
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;
    client.connect({onSuccess:onConnect});
    function onConnect() {
        // Once a connection has been made, make a subscription and send a message.
        client.publish = function(topic, payload) {
            message = new Paho.MQTT.Message(payload);
            message.destinationName = topic;
            client.send(message);
        }
        console.log("状态：连接服务器成功！");
        client.subscribe(device_id+'/out/#', {qos: 0});
    }
    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0)
            console.log("onConnectionLost:"+responseObject.errorMessage);
    }
    function onMessageArrived(message) {
        console.log(message.destinationName + ':? ' + message.payloadString);
        if ( message.destinationName == (device_id + '/out/read') ) {
            var json_obj = JSON.parse(message.payloadString); 
            if ( json_obj != null ) {
                for (var k in json_ojb) {
                    if ( k == '17') {
                            document.getElementById('temp').innerHTML = 'T: ' + json_obj[k];
                    }
                    else if ( k ==  '19'){
                        document.getElementById('temp').innerHTML = 'H: ' + json_obj[k];
                    }
                    else{}
                };
            }
        }
    }
 }

angular.module('ionicApp', ['ionic'])

.controller('MyCtrl', function($scope,$ionicPopup,$http) {
    var device_id = getParameterByName('device_id');
    var access_token = getParameterByName('access_token');
    $scope.a_data =[
                {id:"101010100",name:"北京"},{id:"101020100",name:"上海"},
                {id:"101280101",name:"广东"},{id:"101030100",name:"天津"},
                {id:"101040100",name:"重庆"},{id:"101090101",name:"河北"},
                {id:"101190101",name:"江苏"},{id:"101200101",name:"湖北"},
                {id:"101210101",name:"浙江"},{id:"101060103",name:"吉林"},
                {id:"101070101",name:"辽宁"},{id:"101100101",name:"山西"},
                {id:"101110101",name:"陕西"},{id:"101120101",name:"山东"},
                {id:"101130101",name:"新疆"},{id:"101150101",name:"青海"},
                {id:"101160101",name:"甘肃"},{id:"101170101",name:"宁夏"},
                {id:"101180101",name:"河南"},{id:"101220101",name:"安徽"},
                {id:"101230101",name:"福建"},{id:"101240101",name:"江西"},
                {id:"101250101",name:"湖南"},{id:"101260101",name:"贵州"},
                {id:"101270101",name:"四川"},{id:"101290101",name:"云南"},
                {id:"101300101",name:"广西"},{id:"101140101",name:"西藏"},
                {id:"101080101",name:"内蒙古"},{id:"101050101",name:"黑龙江"},
                {id:"101310101",name:"海南"},{id:"101320101",name:"香港"},
                {id:"101330101",name:"澳门"},{id:"101340101",name:"台湾"}
            ];
//$scope.data_GPS="101020100";
$scope.reloadPage = function() {
 $http.post(
   'http://api.easylink.io/v1/device/property/set',
      {
       device_id : device_id,
       name      : "GPS",
       value     : $scope.data_GPS
     },{
     headers : {
       'AUTHORIZATION' : "token " + access_token
     }
   }
   ).success(function(data) {
        //alert("成功！");
        var alertPopup = $ionicPopup.alert({
       title: '设置成功！',
       okType: 'button-calm'
     });
        console.log("操作：更新城市设置成功！");
    }
   ).error(function(data) {
        alert("失败！");
   return;
 });  
}
$scope.InitPage = function() {
 $http.post(
   'http://www.easylink.io/v1/device/property/list',
   {device_id : device_id
   },{
   headers : {
       'AUTHORIZATION' : "token " + access_token
     }
   }
   ).success(function(data) {
    for ( var i in data ) {
      var device = data[i];
      if ( device === null ) continue;
      if (device.name=="GPS" )
        //alert(device.value);
        $scope.data_GPS=device.value;
    }
  }).error(function(data) {
    //alert(data.error.message);
    alert("失败！");
   return;
 });  
}
$scope.tapSend = function() {
// 留言数据发送部分
var inputMessage = document.getElementById('message');
if ( inputMessage.value.length == 0 ) return;
if (inputMessage.value.length >36) 
   {alert("字数超过36个字"); return;}
$http.post(
   'http://api.easylink.io/v1/device/property/set',
      {
       device_id : device_id,
       name      : "word",
       value     : inputMessage.value
     },{
     headers : {
       'AUTHORIZATION' : "token " + access_token
     }
   }
   ).success(function(data) {
      //alert("成功！");
      var alertPopup = $ionicPopup.alert({
       title: '发送成功！',
       okType: 'button-calm'
     });
      console.log("操作：已发送:"+inputMessage.value);
    }
   ).error(function(data) {
        alert("失败！");
   return;
 });  
}

}); 
</script>
</body>
</html>